package ch.wanandroid.model;

import android.util.Log;

import java.util.ArrayList;
import java.util.List;

import ch.wanandroid.api.HomePageApi;
import ch.wanandroid.lib.banner.BannerItem;
import ch.wanandroid.lib.net.RetrofitClient;
import ch.wanandroid.lib.net.beans.ArticleResponse;
import ch.wanandroid.lib.net.beans.BannerResponse;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;

/**
 * Author: ch
 * Date: 2018/10/22 14:21
 * Description: ${DESCRIPTION}
 */

public class HomeModelImpl implements IHomeModel {
    Retrofit mRetrofit;
    HomePageApi api;

    public HomeModelImpl() {
        mRetrofit = RetrofitClient.getInstance();
        api = mRetrofit.create(HomePageApi.class);
    }

    @Override
    public void loadBannerData(final OnLoadCompleteListener listener) {
        api.getBanner()
                .subscribeOn(Schedulers.io())
                .map(new Function<BannerResponse, List<BannerItem>>() {

                    @Override
                    public List<BannerItem> apply(BannerResponse bannerResponse) throws Exception {
                        List<BannerItem> mBannerItemList=new ArrayList<>();
                        for (int i=0;i<bannerResponse.getData().size();i++){
                            BannerItem bannerItem=new BannerItem();
                            bannerItem.title=bannerResponse.getData().get(i).getTitle();
                            bannerItem.imgUrl=bannerResponse.getData().get(i).getImagePath();
                            mBannerItemList.add(bannerItem);
                        }
                        return mBannerItemList;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<BannerItem>>() {
                    @Override
                    public void accept(List<BannerItem> bannerResponse) throws Exception {
                        listener.onComplete(bannerResponse);
                    }
                });
    }

    @Override
    public void loadHomeData(final HomeCompleteListener listener, int page) {
        api.getHomeArticle(page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ArticleResponse>() {
                    @Override
                    public void accept(ArticleResponse articleResponse) throws Exception {
                        listener.onComplete(articleResponse);
                    }
                });
    }

}
